from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import uuid
import time

app = FastAPI(title="Mini AI Backend")

# 功能列表
features = {
    "zh2en": "中文翻译英文",
    "en2zh": "英文翻译中文",
    "summary": "文本总结"
}


# 请求体模型
class TaskRequest(BaseModel):
    func: str
    text: str

# 路由
@app.get("/features")
async def get_features():
    return {"features": features}

# 异步任务执行
@app.post("/run", status_code=202)
async def run_task(req: TaskRequest, background_tasks: BackgroundTasks):
    # 错误处理
	if req.func not in features:
        raise HTTPException(status_code=400, detail="Unknown function")
    
	# 生成唯一ID
    task_id = str(uuid.uuid4())
    tasks[task_id] = {"status": "queued", "result": None}

    # 将任务推入后台执行
    background_tasks.add_task(_execute_task, task_id, req.func, req.text)
    return {"task_id": task_id, "status": "queued"}


@app.get("/result/{task_id}")
async def get_result(task_id: str):
	# 错误处理
    if task_id not in tasks:
        raise HTTPException(status_code=404, detail="Task not found")
    return {"task_id": task_id, **tasks[task_id]}

# 任务回调
def _execute_task(task_id: str, func: str, text: str):
    tasks[task_id]["status"] = "running"

	# 调用大模型
    time.sleep(2)  

	# 结果拼装
    prompt = _build_prompt(func, text)
    tasks[task_id]["result"] = f"[Response for: {prompt}]"
    tasks[task_id]["status"] = "finished"

def _build_prompt(func: str, text: str) -> str:
    mapping = {
        "zh2en": "中译英: ",
        "en2zh": "英译中: ",
        "summary": "文本总结: "
    }
    return mapping.get(func, "") + text

# 启动
if __name__ == "__main__":
    import uvicorn
    uvicorn.run("main:app", host="0.0.0.0", port=8080, reload=True)
